package com.wcs.exam.controller.admin.biz;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.PageDTO;
import com.wcs.exam.common.base.Result;
import com.wcs.exam.common.base.page.Page;
import com.wcs.exam.common.base.page.PageUtil;
import com.wcs.exam.common.util.BeanUtil;
import com.wcs.exam.common.base.BaseBiz;
import com.wcs.exam.dao.UserAttendanceDao;
import com.wcs.exam.dao.impl.mapper.entity.UserAttendance;
import com.wcs.exam.controller.admin.req.AdminUserAttendanceEditReq;
import com.wcs.exam.controller.admin.req.AdminUserAttendancePageReq;
import com.wcs.exam.controller.admin.req.AdminUserAttendanceSaveReq;
import com.wcs.exam.controller.admin.req.AdminUserAttendanceSortReq;
import com.wcs.exam.controller.admin.resp.AdminUserAttendancePageResp;
import com.wcs.exam.controller.admin.resp.AdminUserAttendanceViewResp;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import jakarta.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * Admin-用户考勤
 *
 * @author wcs
 * @since 2025-03-13
 */
@Component
@RequiredArgsConstructor
public class AdminUserAttendanceBiz extends BaseBiz {

    @NotNull
    private final UserAttendanceDao dao;

    /**
     * 用户考勤-分页
     *
     * @param req 用户考勤-分页查询参数
     * @return 用户考勤
     */
    public Result<Page<AdminUserAttendancePageResp>> page(AdminUserAttendancePageReq req) {
        // 处理查询条件
        LambdaQueryWrapper<UserAttendance> wrapper = new LambdaQueryWrapper<>();
        // 排序
        wrapper.orderByDesc(UserAttendance::getSort);
        wrapper.orderByDesc(UserAttendance::getId);

        // 分页查询
        IPage<UserAttendance> page = dao.page(PageDTO.of(req.getPageCurrent(), req.getPageSize()), wrapper);
        Page<AdminUserAttendancePageResp> resp = PageUtil.transform(page, AdminUserAttendancePageResp.class);
        return Result.success(resp);
    }

    /**
     * 用户考勤-添加
     *
     * @param req 用户考勤
     * @return 添加结果
     */
    public Result<String> save(AdminUserAttendanceSaveReq req) {
        UserAttendance userAttendance = BeanUtil.copyProperties(req, UserAttendance.class);
        userAttendance.setSort(dao.getMaxSort() + 1);
        if (dao.save(userAttendance)) {
            return Result.success(toI18nSuccess());
        }
        return Result.error(toI18nFail());
    }

    /**
     * 用户考勤-查看
     *
     * @param id 主键ID
     * @return 用户考勤
     */
    public Result<AdminUserAttendanceViewResp> view(Long id) {
        UserAttendance userAttendance = dao.lambdaQuery()
                .eq(UserAttendance::getId, id)
                .one();
        if (ObjectUtil.isNull(userAttendance)) {
            return Result.error("用户考勤不存在");
        }
        return Result.success(BeanUtil.copyProperties(userAttendance, AdminUserAttendanceViewResp.class));
    }

    /**
     * 用户考勤-编辑
     *
     * @param req 用户考勤-编辑对象
     * @return 编辑结果
     */
    public Result<String> edit(AdminUserAttendanceEditReq req) {
        // 获取校验用户考勤
        UserAttendance userAttendance = dao.lambdaQuery()
                .eq(UserAttendance::getId, req.getId())
                .one();
        if (ObjectUtil.isNull(userAttendance)) {
            return Result.error("用户考勤不存在");
        }

        // 更新用户考勤
        UserAttendance updateUserAttendance = BeanUtil.copyProperties(req, UserAttendance.class);
        updateUserAttendance.setGmtCreate(null);
        updateUserAttendance.setGmtModified(null);
        if (dao.updateById(updateUserAttendance)) {
            return Result.success(toI18nSuccess());
        }
        return Result.error(toI18nFail());
    }

    /**
     * 用户考勤-排序
     *
     * @param reqs 用户考勤-排序对象
     * @return 排序结果
     */
    public Result<String> sort(List<AdminUserAttendanceSortReq> reqs) {
        // 查询获取用户考勤
        List<UserAttendance> userAttendanceList = dao.lambdaQuery()
            .in(UserAttendance::getId, reqs.stream().map(AdminUserAttendanceSortReq::getId).collect(Collectors.toSet()))
            .list();
        if (CollectionUtil.isEmpty(userAttendanceList)) {
            return Result.success(toI18nSuccess());
        }

        // 处理待更新排序的用户考勤
        Map<Long, Integer> sortMap = new HashMap<>();
        reqs.forEach(item -> sortMap.put(item.getId(), item.getSort()));
        List<UserAttendance> updateList = new ArrayList<>();
        for (UserAttendance userAttendance : userAttendanceList) {
            Integer sort = sortMap.get(userAttendance.getId());
            if (ObjectUtil.isNull(sort)) {
                continue;
            }

            UserAttendance updateUserAttendance = new UserAttendance();
            updateUserAttendance.setId(userAttendance.getId());
            updateUserAttendance.setSort(sort);
            updateList.add(updateUserAttendance);
        }

        // 批量更新用户考勤排序
        if (CollectionUtil.isNotEmpty(updateList)) {
            dao.updateBatchById(updateList);
        }
        return Result.success(toI18nSuccess());
    }

    /**
     * 用户考勤-删除
     *
     * @param id ID主键
     * @return 删除结果
     */
    public Result<String> delete(Long id) {
        // 获取校验用户考勤
        UserAttendance userAttendance = dao.lambdaQuery()
                .eq(UserAttendance::getId, id)
                .one();
        if (ObjectUtil.isNull(userAttendance)) {
            return Result.error("用户考勤不存在");
        }

        // 删除用户考勤
        if (dao.removeById(id)) {
            return Result.success(toI18nSuccess());
        }
        return Result.error(toI18nFail());
    }
}
